<script lang="ts" setup>
import { ref, computed, Ref, reactive, onMounted } from "vue";
import { Edit } from "@element-plus/icons-vue";
import Applicant from "@/types/response/applicant";
import { ElMessage } from "element-plus";
import useFileStore from "@/stores/fileStore";
import {
  createApplicant,
  getAllApplicants,
  updateApplicant,
  getAllInstitutions,
} from "@/axios/applicant/applicantReq";
import { changeUserState, getUserStatesByIds } from "@/axios/admin/accountReq";
import ApplicationInstitution from "@/types/response/applicantIns";
import Notice from "@/utils/notice";
interface ExtendedApplicant extends Applicant {
  state?: number;
}
let fileStore = useFileStore();
const stateOptions = [
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "停用",
  },
];
//用户搜索时输入的名字
const name = ref("");
let insConfig: {
  insts: ApplicationInstitution[]; //所有的申请机构列表
  init: Function; //初始化
  getById: (id: number) => ApplicationInstitution; //根据id获取机构信息
} = reactive({
  insts: [],
  init: async () => {
    getAllInstitutions().then((res) => {
      insConfig.insts = res;
    });
  },
  getById(id) {
    return insConfig.insts.find((inst) => inst.applicationInstitutionId == id);
  },
});
onMounted(() => {
  insConfig.init();
});
// 用户搜索时输入的所属组织
const lawnSite = ref("");

const applicants: Ref<ExtendedApplicant[]> = ref([]);

const rulesFormRef = ref();

// 控制添加申请人弹窗
const dialogVisible = ref(false);

// 添加申请人数据模型
const applicantModel = ref<ExtendedApplicant>(new Applicant());

// 状态选择框绑定的值
const stateValue = ref<number>();

// 获取申请人列表
const getApplicants = async () => {
  let result = await getAllApplicants();
  applicants.value = result;
  let ids = applicants.value.map((admin) => admin.applicantId);
  let states = await getUserStatesByIds(ids);
  for (let applicant of applicants.value) {
    applicant.state = states.get(applicant.applicantId);
  }
};
getApplicants();

// 添加申请人表单校验
const rules = {
  name: [{ required: true, message: "请输入申请人姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入电话号码", trigger: "blur" }],
  idNum: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
};
//添加申请人函数
const addApplicant = () => {
  title.value = "新增申请人";
  applicantModel.value = new Applicant();
  dialogVisible.value = true;
  stateValue.value = 1; //添加申请人信息
  editIndex.value = null; //将当前索引设置为空 那么就是 修改申请人的信息
  rulesFormRef.value?.resetFields();
};
const editIndex = ref<number | null>(null); //当前 编辑的申请人的索引

const editApplicant = (index: number, applicant: ExtendedApplicant) => {
  title.value = "编辑申请人";
  dialogVisible.value = true;
  applicantModel.value = { ...applicant };
  stateValue.value = applicant.state;
  editIndex.value = index;
  rulesFormRef.value?.clearValidate();
};

const validateForm = () => {
  rulesFormRef.value.validate((valid) => {
    if (valid) {
      submitForm();
    }
  });
};

// 提交表单的方法
const submitForm = async () => {
  if (stateValue.value) {
    applicantModel.value.state = stateValue.value;
  }
  //更新申请人信息
  if (editIndex.value !== null) {
    applicants.value[editIndex.value] = { ...applicantModel.value };
    editIndex.value = null;
    const success = await updateApplicant(applicantModel.value);
    if (success) {
      ElMessage({
        type: "success",
        message: "申请人更新成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "申请人更新失败",
      });
    }
  } else {
    // 调用创建接口
    const applicant = await createApplicant(applicantModel.value);
    if (applicant) {
      applicants.value.push(applicant);
      Notice.success("创建成功");
    } else {
      Notice.error("创建失败");
    }
    applicantModel.value = new Applicant();
    stateValue.value = 1;
  }
  // 这里可以添加保存到 applicants 数组的逻辑
  dialogVisible.value = false;
};

// 切换申请人状态的方法
const toggleState = async (applicant: any) => {
  try {
    const newState = applicant.state === 1 ? 0 : 1;
    const success = await changeUserState(applicant.applicantId, newState);
    if (success) {
      applicant.state = newState;
      ElMessage({
        type: "success",
        message: "状态切换成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "状态切换失败",
      });
    }
  } catch (error) {
    console.error("切换状态时出错:", error);
  }
};

const title = ref("");

const filteredApplicants = computed(() => {
  return applicants.value.filter(
    (applicant) =>
      (!name.value || applicant.name.includes(name.value)) &&
      (!lawnSite.value || applicant.lawnSite === lawnSite.value)
  );
});
//详细信息抽屉
const table = ref(false);
const selectedApplicants: Ref<Applicant> = ref(null);

const openDrawer = (respondent: any) => {
  selectedApplicants.value = respondent;
  table.value = true;
};
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>申请人管理</span>
        <div class="extra">
          <el-button type="primary" @click="addApplicant">新增申请人</el-button>
        </div>
      </div>
    </template>
    <!-- 搜素表单 -->
    <el-form inline>
      <el-form-item label="姓名：">
        <el-input
          v-model="name"
          style="width: 240px"
          clearable
          placeholder="请输入筛选姓名"
        />
      </el-form-item>
      <!--
      <el-form-item label="所属机构：">
        <el-select v-model="lawnSite" style="width: 240px" clearable placeholder="请选择事务所">
          <el-option
            v-for="institution in insConfig.insts"
            :key="institution"
            :label="institution"
            :value="institution"
          />
        </el-select>
      </el-form-item>
      -->
    </el-form>

    <el-table :data="filteredApplicants" style="width: 100%">
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="电话号码" prop="phone"></el-table-column>
      <el-table-column label="所属事务所" prop="lawnSite"></el-table-column>
      <el-table-column label="状态" prop="state">
        <template #default="scope">
          {{
            stateOptions.find((s) => s.value === scope.row.state)?.label ||
            "未知"
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            :disabled="scope.row.state === 0"
            @click="editApplicant(scope.$index, scope.row)"
          ></el-button>
          <el-button
            :type="scope.row.state === 1 ? 'danger' : 'success'"
            circle
            plain
            @click="toggleState(scope.row)"
          >
            {{
              stateOptions.find((s) => s.value === scope.row.state)?.label ===
              "启用"
                ? "停用"
                : "启用"
            }}
          </el-button>
          <el-button text type="primary" @click="openDrawer(scope.row)"
            >详细</el-button
          >
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="applicantModel"
        :rules="rules"
        label-width="130px"
        style="padding-right: 30px"
        ref="rulesFormRef"
      >
        <el-form-item label="申请人姓名" prop="name">
          <el-input
            v-model="applicantModel.name"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNum">
          <el-input
            v-model="applicantModel.idNum"
            minlength="18"
            maxlength="18"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证照片" prop="idImg">
          <el-button
            v-if="!applicantModel.idImg"
            type="primary"
            @click="
              () => {
                fileStore.selectFileToUpload('all', (res) => {
                  applicantModel.idImg = res.remoteUrl;
                });
              }
            "
            >上传证明</el-button
          >
          <el-image
            v-if="applicantModel.idImg"
            :src="applicantModel.idImg"
            fit="fill"
            @click="
              () => {
                fileStore.selectFileToUpload('all', (res) => {
                  applicantModel.idImg = res.remoteUrl;
                });
              }
            "
          ></el-image>
        </el-form-item>
        <el-form-item label="律师证号" prop="lawnNum">
          <el-input v-model="applicantModel.lawnNum"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input
            v-model="applicantModel.phone"
            :disabled="editIndex !== null"
            minlength="11"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="applicantModel.email"
            minlength="2"
            maxlength="18"
          ></el-input>
        </el-form-item>
        <el-form-item label="律师事务所" prop="lawnSite">
          <el-input
            v-model="applicantModel.lawnSite"
            minlength="2"
            maxlength="18"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属金融机构">
          <el-select v-model="applicantModel.insId">
            <el-option
              v-for="item in insConfig.insts"
              :key="item.applicationInstitutionId"
              :label="item.name"
              :value="item.applicationInstitutionId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
  <el-drawer v-model="table" title="申请人详细信息" direction="rtl" size="50%">
    <el-descriptions :column="1" border :data="selectedApplicants">
      <el-descriptions-item label="姓名">{{
        selectedApplicants?.name
      }}</el-descriptions-item>
      <el-descriptions-item label="身份证号">{{
        selectedApplicants?.idNum
      }}</el-descriptions-item>
      <el-descriptions-item label="身份证照片">
        <el-image
          style="width: 100px; height: 100px"
          :src="selectedApplicants?.idImg"
          fit="cover"
        />
      </el-descriptions-item>
      <el-descriptions-item label="手机号">{{
        selectedApplicants?.phone
      }}</el-descriptions-item>
      <el-descriptions-item label="电子邮箱">{{
        selectedApplicants?.email
      }}</el-descriptions-item>
      <el-descriptions-item label="律师证号">{{
        selectedApplicants?.lawnNum
      }}</el-descriptions-item>
      <el-descriptions-item label="律师事务所">{{
        selectedApplicants?.lawnSite
      }}</el-descriptions-item>
      <el-descriptions-item label="金融机构">{{
        insConfig.getById(selectedApplicants.insId).name
      }}</el-descriptions-item>
    </el-descriptions>
  </el-drawer>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
